package com.openblockhos.slice;

import com.openblockhos.DeviceDialog;
import com.openblockhos.MainAbility;
import com.openblockhos.ResourceTable;
import com.openblockhos.Runtime;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.IntentParams;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Component;
import ohos.agp.components.webengine.JsCallback;
import ohos.agp.components.webengine.WebConfig;
import ohos.agp.components.webengine.WebView;
import ohos.agp.window.dialog.CommonDialog;
import ohos.agp.window.dialog.IDialog;
import ohos.agp.window.service.Window;
import ohos.app.Environment;
import ohos.bundle.ElementName;
import ohos.data.file.FileAbility;
import ohos.utils.net.Uri;

import java.io.*;
import java.util.Base64;

public class MainAbilitySlice extends AbilitySlice {
    Base64.Decoder decoder = Base64.getDecoder();
    private String DeviceIdToRun;
    private DeviceDialog deviceDialog;

    @Override
    public void onStart(Intent intent) {
        deviceDialog = new DeviceDialog(getContinuationRegisterManager(), MainAbilitySlice.this);
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        WebView webView = (WebView) findComponentById(ResourceTable.Id_webview);
        webView.setWebAgent(new OBWebAgent(webView));
        webView.setBrowserAgent(new OBBrowserAgent(this.getContext(),webView));
        WebConfig wcfg = webView.getWebConfig();

        wcfg.setUserAgent(wcfg.getUserAgent().replaceAll("Android","HarmonyOS"));
        wcfg.setJavaScriptPermit(true);
        wcfg.setWebStoragePermit(true);
        wcfg.setTextAutoSizing(true);
//        webView.setFocusChangedListener(new Component.FocusChangedListener() {
//            @Override
//            public void onFocusChange(Component component, boolean b) {
//
//            }
//        });
//        wcfg.setViewPortFitScreen(true);
        webView.addJsCallback("OpenBlockXENativeConfig", new JsCallback() {
            @Override
            public String onCallback(String s) {
//                CommonDialog dialog = new CommonDialog(getContext());
//                dialog.setTitleText("Notification");
//                dialog.setContentText("This is CommonDialog Content area.");
//                dialog.setButton(IDialog.BUTTON3, "CONFIRM", (iDialog, i) -> iDialog.destroy());
//                dialog.show();

                // 打开设备选择框（连接）
                deviceDialog.showDeviceList();
                return "OK";
            }
        });
        webView.addJsCallback("OpenBlockXENativeRun", new JsCallback() {
            @Override
            public String onCallback(String msg) {
                // 增加自定义处理
                byte[] b = decoder.decode(msg);
//                ByteArrayInputStream s = new ByteArrayInputStream(b);
                File distDir = MainAbilitySlice.this.getDistributedDir();//.getDistributedDir();//.getDistributedDir();//.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);//.getDataDir();
                String filePath = distDir + File.separator + "main.xe";
                try {
                    File file = new File(filePath);
                    file.delete();
                    FileOutputStream o = new FileOutputStream(filePath, false);
                    o.write(b);
                    o.close();
                    IntentParams intentParams = new IntentParams();
                    intentParams.setParam("exFilePath", filePath); //
                    // Jump to RightAbility split screen
//                    intentParams.setParam("file",file);
//                    Uri uri = FileAbility.getUriViaFile(getContext(), "/ohos.data.file.FileAbility ", file);
                    Intent intent = new Intent();
                    if (DeviceIdToRun != null && DeviceIdToRun != "") {
                        Operation op = new Intent.OperationBuilder()
                                .withDeviceId(DeviceIdToRun)
                                .withBundleName(getBundleName())
                                .withAbilityName(Runtime.class.getName())
                                .withFlags(Intent.FLAG_ABILITYSLICE_MULTI_DEVICE)
                                .build();
                        intent.setOperation(op);
                    } else {
                        ElementName element = new ElementName(MainAbilitySlice.this.DeviceIdToRun, MainAbilitySlice.this.getBundleName(), Runtime.class.getName());
                        intent.setElement(element);
                    }
                    intent.addFlags(0x00000001);
                    intent.addFlags(Intent.FLAG_NOT_OHOS_COMPONENT);
//                    intent.setUriAndType(uri, "*");
                    intent.setParams(intentParams);
                    MainAbilitySlice.this.startAbility(intent);
                    return "OK";
                } catch (IOException e) {
                    System.err.println(e);
                }
                return "fail";
            }
        });
//       final String url = "http://192.168.0.10/testing/"; //列表
         final String url = "https://www.makeredu.net/openblock/frontpage/index.html#%7B%22proj%22:%22/testing/canvas/Canvas%E5%9D%90%E6%A0%87.json%22%7D"; // 画板
        webView.load(url);
//        webView.load("123","text",false);
    }

    @Override
    public void onActive() {
//        super.onActive();
    }

    @Override
    protected void onInactive() {
//        super.onInactive();
    }

    @Override
    public void onForeground(Intent intent) {
//        super.onForeground(intent);
    }

    public void setDeviceId(String selectDeviceId) {
        this.DeviceIdToRun = selectDeviceId;
        System.out.println("New Device Selected:" + selectDeviceId);
    }

    @Override
    protected void onStop() {
        super.onStop();

        // 断开流转任务管理服务
        deviceDialog.clearRegisterManager();
    }
}
